<!--
 * @Author: gongjiuhui
 * @Date: 2022-04-18 09:49:04
 * @LastEditTime: 2023-07-05 15:17:48
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \jk_one-stop_cloud_mobile_v1.0\src\views\apply\applyDeliver.vue
-->
<template>
  <div>
    <Navbar :appTitle="title" />
    <div class="search-content wrap-apply"  :style="{top: GLOBAL.currentEnvironment ? '0.1rem' : '0.52rem',height: GLOBAL.currentEnvironment ? '100vh' : 'calc(100vh - 1.12rem)',paddingBottom: GLOBAL.currentEnvironment ? '0.66rem' : ''}">
      <van-cell-group>
        <p class="label required FormTit"><span></span>客户名称</p>
        <van-field-select-picker label="" :supportClear='true' placeholder="请选择" v-model="buildForm.customerId" :columns="customerList" :option="{ label: 'customerFullName', value: 'id' }"
          @confirm="peopleConfirm" @prePopShow="showPeopleDialog" />
        <div class="bottomLine"></div>
      </van-cell-group>
      <van-cell-group>
        <p class="label required FormTit"><span></span>销售合同</p>
         <van-field-select-picker label="" :supportClear='true' placeholder="请选择" v-model="buildForm.contractId" :columns="contractList" :option="{ label: 'contractName', value: 'id' }"
          @confirm="contractConfirm" @prePopShow="showContractDialog" />
        <div class="bottomLine"></div>
      </van-cell-group>
       <van-cell-group>
        <p class="label required FormTit"><span></span>承诺交期</p>
        <van-field readonly v-model="buildForm.promiseDate" placeholder="请先选择销售合同" />
        <div class="bottomLine"></div>
      </van-cell-group>
       <van-cell-group style='margin-top:0.1rem'>
        <p class="label required FormTit"><span></span>领用人</p>
        <van-field
          is-link
          readonly
          name="picker"
          v-model="receiveByName"
          @click="ddthrVisible = true"
          placeholder="请选择"
          :rules="[{ required: true, message: '请选择领用人' }]"
        >
          <template slot="right-icon" v-if="buildForm.receiveBy">
            <img
              src="~@/assets/img/filedClear.png"
              alt=""
              @click.stop="confirmDdtjr('', [], true)"
              style="width: 0.16rem; height: 0.16rem"
            />
          </template>
        </van-field>
      </van-cell-group>
      <van-cell-group>
        <p class="label required FormTit"><span></span>发货日期</p>
        <van-field
          is-link
          readonly
          name="picker"
          v-model="buildForm.shippingDate"
          @click="receiveTimeModal = true"
          placeholder="请选择"
          :key="dateKey"
        >
          <template slot="right-icon" v-if="buildForm.shippingDate">
            <img
              src="~@/assets/img/filedClear.png"
              alt=""
              @click.stop="clickClose"
              style="width: 0.16rem; height: 0.16rem"
            />
          </template>
        </van-field>
      </van-cell-group>
      <van-cell-group>
        <p class="label">发货备注</p>
        <van-field v-model="buildForm.remark" rows="2" autosize label="" type="textarea" maxlength="500" placeholder="请输入备注" show-word-limit />
        <div class="bottomLine"></div>
      </van-cell-group>
     
      <van-cell-group style='margin-top:0.1rem' v-for="(item,index) in selectedRows" :key="index"> 
          <div class="label otherText vcmiddle">
         <span>发货明细{{index +1}}</span>
         <img
          class="delimg"
          @click="deleteGoods(index)"
          src="@/assets/img/delete.png"
         
        />
          </div>
        <div class="bottomLine"></div>
       
        <p class="label required FormTit"><span></span>商品编号|商品名称</p>
        <!-- <van-field readonly v-model="buildForm.promiseDate" placeholder="请先选择" /> -->
        <div class="label-context">{{item.goodsCode}}|{{item.goodsName}}</div>
        <div class="bottomLine"></div><div class="bottomLine"></div>
        <p class="label required FormTit"><span></span>规格</p>
        <!-- <van-field readonly v-model="buildForm.promiseDate" placeholder="请先选择" /> -->
        <div class="label-context">{{item.spec}}</div>
        <div class="bottomLine"></div><div class="bottomLine"></div>
        <p class="label required FormTit"><span></span>本次发货数量<span v-if="item.unit">({{item.unit}})</span></p>
        <van-field  v-model="item.shippedNum" placeholder="请先输入"  @change="(item) => inputChange(item, index)" />
        <div class="bottomLine"></div><div class="bottomLine"></div>
        <div class="bottomContent">
            本合同订购数量<span class="num">{{item.saleNum}}{{item.unit}}</span>，订购基本数量<span  class="num">{{item.saleBasicNum}}{{item.basicUnit}}</span>。
            已申请发货数量<span  class="num">{{item.shippingNum}}{{item.unit}}</span>，可剩余发货数量<span  class="num">{{item.availableShippingNum}}{{item.unit}}</span>。
        </div>
         <div class="bottomLine"></div><div class="bottomLine"></div>
      </van-cell-group>
      <div class="addbtn" @click="chooseGood"><van-icon class="vicon" name="plus" size="18" color="#1890ff" />选择发货商品</div>
       <van-cell-group style="margin-top: 0.12rem">
        <!-- <upload iconType="fj" @fileChange="fileChange" :fileIds="buildForm.attachment" /> -->
        <fileSelector
          iconType="fj"
          :title="'附件'"
          @fileChange="fileChange"
          :fileIds="buildForm.attachment"
        ></fileSelector>
      </van-cell-group>
      <div style="margin-top: 0.12rem">
        <Examine @submitProcess="submitProcess"  type="0" :key="examKey" id="ERP_SHIPPING_APPLY" ref="examine" />
        <div style="height: 0.26rem"></div>
      </div>
      <div class="search-bottom">
        <span class="btnconfirm" @click="btnConfirm('finish')">提交</span>
      </div>
    </div>
    <choose-tag
      :contractId="contractId"
      ref="chooseTag"
      v-if="showChooseTag"
      @chooseTag="chooseTag"
    ></choose-tag>
    <!--发货日期 -->
    <van-popup v-model="receiveTimeModal" position="bottom">
      <van-datetime-picker
        v-model="nowTime"
        @confirm="confirmReceiveTime"
        @cancel="cancelReceiveTime"
        type="date"
        title="发货日期"
      />
    </van-popup>
    <contact-pickers
      :key="index"
      :visible="ddthrVisible"
      @confirm="confirmDdtjr"
      @closePicker="closePicker"
      :max="1"
    >
    </contact-pickers>
  </div>
</template>
<script>
import { selectCustomerList,erpShippingApplySelectByUserId,erpShippingApplyAdd} from "@/api/mobile.js";
import Navbar from "@/components/navBar/navBar_right";
import scanInput from "@/components/scanCode/scanInput";
import ContactPickers from "@/components/choiceuse/ContactPickers";
import upload from "@/components/upload/upload";
import VanFieldSelectPicker from "@/components/ActionSheet/VanFieldSelectPicker";
import VanFieldCheckbox from "@/components/ActionSheet/VanFieldCheckbox";
import moment from "moment";
import Examine from "@/components/examine";
import ChooseTag from "./chooseTag";
import fileSelector from "@/components/fileSelector.vue";
export default {
  name: "search",
  components: {
    ContactPickers,
    upload,
    VanFieldSelectPicker,
    VanFieldCheckbox,
    Navbar,
    scanInput,
    Examine,
    ChooseTag,
    fileSelector
  },
  data() {
    return {
      title:"发货申请",
      contractId:"",
      showChooseTag:false,
      taskId: "",
      orderId: "",
      notQualifiedReason: [],
      customerList:[],//客户 
      contractList:[],//销售合同
      selectedRows:[],
      buildForm: {
        taskId: "",
        customerId: "",
        contractId:"",
        promiseDate:"",
        remark: "",
        attachment:""
      },
      dictOptions: [], //不合格原因
      createdByName: "", //操作人
      columns: [],
      workOrderList: [], //完整的工单编号列表
      taskList: [], //工序列表
      operatorList: [], //操作人
      attachment: "", //附件
      subimtType: "",
      examKey: 1,
      formPage: "",
      currentLoginUser: {},
      receiveTimeModal: false,
      nowTime: new Date(),
      dateKey: 1.1,
      ddthrVisible: false,
      receiveByName: '',
      index: 1.2
    };
  },
  computed: {},
  mounted() {},
  created() {
    this.getInitData()
  },
   beforeRouteLeave(to, from, next) {
    let that = this;
    switch (true) {
      case that.showChooseTag:
        that.showChooseTag = false;
        this.title = "申请发货";
        next(false);
        break;
      case !that.showChooseTag:
        next();
        break;
    }
  },
  methods: {
    // 选人
    confirmDdtjr(val, selectedList, judge) {
      this.buildForm.receiveBy = "";
      this.receiveByName = "";
      if (judge) {
        this.ddthrVisible = false;
        return;
      }
      this.buildForm.receiveBy = val ? val : ""; //人员id
      let arr = [];
      if (selectedList) {
        selectedList.forEach((item) => {
          arr.push(item.realname);
        });
      }
      this.receiveByName = arr.join(",");
      this.ddthrVisible = false;
    },
    // 关闭选人组件
    closePicker() {
      this.ddthrVisible = false;
    },
    // 选择时间
    confirmReceiveTime(date) {
      this.buildForm.shippingDate = moment(date).format("YYYY-MM-DD");
      this.receiveTimeModal = false;
    },
    // 取消选择时间
    cancelReceiveTime() {
      this.receiveTimeModal = false;
    },
    clickClose() {
      console.log(this.buildForm.shippingDate);
      this.buildForm.shippingDate = ''
      this.dateKey += 1
    },
    //
    deleteGoods(index){
      // this.selectedRows.findIndex(index)
       this.selectedRows.splice(index, 1);
    },
    inputChange(e, i) {
      let newNum = e.target.value
      this.selectedRows[i].shippedNum = newNum
      this.selectedRows.splice()
    },
    chooseGood(){
      if(!this.contractId){
         this.$toast("请选择销售合同");
      }else{
         this.showChooseTag=true
         this.title="选择发货商品"
      }
     
    },
    chooseTag(item){
      console.log(item)
    
      
     if(this.selectedRows.findIndex((element)=>(element.id ==item.id))!=-1){
           this.$toast("您已选择过该商品");
     }else{
        this.title = "申请发货";
         if(!item.shippedNum){
           item.shippedNum = item.saleNum - item.shippingNum
         }
          item.contractItemId = item.id
          this.selectedRows.push(item)
          this.showChooseTag=false
     }
  
    },
    
    //页面加载请求数据
    getInitData() {
      //客户
      selectCustomerList({}).then((res) => {
        if (res.success) {
           console.log(res, '下拉客户')
           this.customerList = res.result
        } else {
          this.$toast(res.message);
        }
      });
    },
    selectByUserId(id) {
      erpShippingApplySelectByUserId(id).then((res) => {
        console.log(res, '选择客户 取销售合同')
        this.contractList = res.result
      })
    },
    peopleConfirm(itemPeople) {
      console.log(itemPeople)
        this.buildForm.contractId=""
        this.buildForm.promiseDate=""
      if(itemPeople){
        this.buildForm.customerId = itemPeople.id;
        this.selectByUserId(itemPeople.id)
      }else{
        this.buildForm.customerId=""
         this.contractList =[]
      }
      
       this.selectedRows=[]

    },
    showPeopleDialog(callback) {
       callback("show");
    },

    //确认合同
    contractConfirm(obj){
       console.log(obj, 'obj0.0.0.')
      this.buildForm.contractId = obj.id;
      let item = this.contractList.filter((each) => each.id == obj.id)
      console.log(item, 'item0.0.0.')
      if(item.length==0){
        this.buildForm.promiseDate=""
      }else{
         this.buildForm.promiseDate=item[0].promiseDate
         this.contractId=obj.id
      }
      this.selectedRows=[]
        
    },
    //显示合同
    showContractDialog(callback){
       callback("show");
    },
    //
    fileChange(item){
      console.log(item)
      this.buildForm.attachment=item
  
    },
     // 提交
    btnConfirm() {
        
      if (!this.buildForm.customerId) {
        this.$toast("请选择客户");
        return;
      }
      if (!this.buildForm.contractId) {
        this.$toast("请选择销售合同");
        return;
      }
      if (!this.buildForm.promiseDate) {
        this.$toast("请输入承诺交期");
        return;
      }
      let isOver=false;
      this.selectedRows.forEach((item,index)=>{
        if(item.shippedNum>item.availableShippingNum){
           
           isOver=true
           return 
          
        }
      }) 
      if(isOver){
        this.$toast("发货数量不能大于可发货数量");
        return 
      }


      let isZs=false;
      let rr= /^\d+(\.\d{1,4})?$/
     
      this.selectedRows.forEach((item,index)=>{
        if(!rr.test(item.shippedNum)){
           isZs=true
           return 
          
        }
      }) 
      if(isZs){
        this.$toast("发货数量不合法：输入数字，最多4位小数");
        return 
      }
     
      this.submitProcess();
    },
    submitProcess(e){
        if (e && e.nodeDtos) {
        // 获取到数据后写表单提交的方法
        this.handleSubmit(e);
      } else {
        // 调用子组件的方法获取数据
        this.$refs.examine.confirm();
      }
    },
    // 提交
    handleSubmit(processDataVo) {
      
      let params = {
        ...this.buildForm,
        type: "production",
        processDataVo: processDataVo,
        erpShippingApplyItemSaveDtoList: this.selectedRows
      };
      
      console.log("检查一下参数：", params);
      erpShippingApplyAdd(params).then((res) => {
            if (res.code == 200) {
              this.$toast("申请发货成功！");
              this.$router.go(-1);
            } else {
            
              this.$toast(res.message)
            }
          })
        
    },
   

  },
};
</script>
<style lang="scss" scoped>
@import "@/assets/theme.scss";
.search-content {
  
  //  padding-bottom: 0.5rem;
  position: fixed;
  top: 0.52rem;
  width: 100%;
  height: calc(100vh - 1.12rem);
  background: #f5f5f5;
  overflow: scroll;
  z-index: 99;
  .formgroup {
    background: #ffffff;
    // padding: 0 0.16rem;
    margin-top: 0.1rem;
    margin-bottom: 0.2rem;
    padding-top: 0.1rem;

    .title {
      width: 0.58rem;
      height: 0.14rem;
      font-size: 0.15rem;
      font-family: PingFang SC;
      font-weight: 400;
      color: #191f25;
      line-height: 0.05rem;
      margin-left: 0.16rem;
    }
  }
  .search-bottom {
    height: 0.5rem;
    width: 100%;
    background: #ffffff;
    // background: red;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: fixed;
    bottom: 0px;
    padding: 0.11rem;
    .btnconfirm {
      width: 100%;
      height: 0.39rem;
      background: #1890ff;
      border-radius: 0rem;
      text-align: center;
      line-height: 0.39rem;

 
        font-size: 0.16rem;
        font-family: PingFang SC;
        font-weight: 500;
        color: #FFFFFF;
      

    }
    .btncancel {
      width: 1.72rem;
      height: 0.39rem;
      background: #f6f6f6;
      border: 0.01px solid rgba(25, 31, 37, 0.12);
      border-radius: 0rem;
      text-align: center;
      line-height: 0.39rem;
    }
  }
}
.bottomLine {
  height: 0.01rem;
  background-color: #f0f0f0;
  margin: 0 0.16rem;
}
.bottomContent{
    padding:0.17rem;
    .num{
        color:orange;
    }
}
.addbtn{
    background-color: #ffffff;
    vertical-align: middle;
    padding: 0.1rem 0.17rem;
    text-align: center;
    // border: 1px solid red;
    // display: flex;
    margin-top: 0.1rem;
    font-size: 0.16rem;
    font-family: PingFang SC;
    font-weight: 400;
    color: #1890FF;
    .vicon{
        // display: inline-block;
         vertical-align: middle;
         position: relative;
         top: -0.02rem;
    }
}
.otherText {
  padding-bottom: 0.16rem;
  font-size: 0.16rem;
  font-weight: bold;
  color: #191f25;
   width: 100% ; 
}
.label-context{
    padding: 0.16rem;                                          
}
.vcmiddle{
 
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.delimg{
    width: 0.16rem;
    height: 0.16rem;
    float: left;
    // margin-right: 0rem;
   
}
.haveUnitBox {
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  padding-right: 0.16rem;
  /deep/ .van-cell {
    padding-right: 0;
    width: 2.6rem;
  }
  /deep/ .van-field__control {
    max-width: 3rem;
  }
}
/deep/ .van-nav-bar {
  z-index: 99;
}
.search-bottoms {
  width: 100%;
  height: 0.5rem;
  background: #ffffff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: fixed;
  bottom: 0px;
  padding: 0rem 0.11rem;
  box-sizing: border-box;
  font-size: 0.16rem;
  font-weight: 500;
  z-index: 9;
  .btnconfirm {
    flex: 1;
    background: #1890ff;
    box-sizing: border-box;
    height: 0.39rem;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 0.03rem;
    color: #ffffff;
  }
}
</style>
